package com.imist.listener;

import com.imist.cache.LoginCache;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class LoginListener implements HttpSessionAttributeListener {
    private static final String LOGINUSER = "LoginUser";

    public void attributeAdded(HttpSessionBindingEvent se) {
        System.out.println("attributeAdded ");
        String name = se.getName();
        if (name.equals(LOGINUSER)) {
            String value = (String) se.getValue();
            HttpSession session = se.getSession();
            String sessionId = session.getId();

            String sessionId2 = LoginCache.instance().getSessionIdByUsername(value);
            if (sessionId2 == null) {
                //之前没有登陆过
            } else {
                HttpSession session2 = LoginCache.instance().getSessionBySessionId(sessionId2);
                //清理前次session的所有数据,所以此次登陆不会触发attributeReplaced()回调，而是触发attributeAdded（）
                session2.invalidate();
            }
            //将新的session存入缓存
            LoginCache.instance().setSessionIdByUsername(value, sessionId);
            LoginCache.instance().setSessionBySessionId(sessionId, session);
        }
    }

    public void attributeRemoved(HttpSessionBindingEvent se) {

    }

    public void attributeReplaced(HttpSessionBindingEvent se) {

    }
}
